package com.kingdee.pda.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.example.basecommon.utils.PreferencesUtils;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.R;
import com.kingdee.pda.plugins.crash.CacheDirectoryManager;
import com.kingdee.pda.ui.sn_query_edit.SnStatus;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类
 *
 * @author ZhuHuaHua
 * @date 2018/1/9 15:10
 */
public class CommonUtil {
    private static final String TAG = CommonUtil.class.getSimpleName();

    public static List<SnStatus> getSnStatusList() {
        ArrayList<SnStatus> statusList = new ArrayList<>();
        statusList.add(new SnStatus("in_library", "在库"));
        statusList.add(new SnStatus("wh_occupy", "已占用"));
        statusList.add(new SnStatus("wh_out", "已出库"));
        statusList.add(new SnStatus("wh_lose", "已破损"));

        return statusList;
    }

    public static String getStatusName(String status) {
        String statusName = "";
        if ("in_library".equals(status)) {
            statusName = "在库";
        } else if ("wh_occupy".equals(status)) {
            statusName = "已占用";
        } else if ("wh_out".equals(status)) {
            statusName = "已出库";
        } else if ("wh_lose".equals(status)) {
            statusName = "已破损";
        }
        return statusName;
    }

    public static String skuCodeSplit(Context context, String skuCode) {
        String splitCode = "";

        boolean isOpen = PreferencesUtils.getBoolean(context, ConstantPreference.SKUSPLIT_IS_OPEN);
        if (!isOpen) {
            return skuCode;
        }

        int beforeX = PreferencesUtils.getInt(context, ConstantPreference.SKUSPLIT_BEFOREX);
        int afterX = PreferencesUtils.getInt(context, ConstantPreference.SKUSPLIT_AFTERX);

        try {
            switch (PreferencesUtils.getInt(context, ConstantPreference.SKUSPLIT_RADIOBUTTONID)) {
                case R.id.rb_limit:
                    splitCode = skuCode.substring(beforeX - 1, afterX);
                    break;
                case R.id.rb_before_x:
                    splitCode = skuCode.substring(0, beforeX);
                    break;
                case R.id.rb_after_x:
                    splitCode = skuCode.substring(skuCode.length() - afterX);
                    break;
                case R.id.rb_delete_before_x:
                    splitCode = skuCode.substring(beforeX);
                    break;
                case R.id.rb_delete_after_x:
                    splitCode = skuCode.substring(0, skuCode.length() - afterX);
                    break;
            }
        } catch (Exception e) {
            splitCode = "";
        }
        return splitCode;
    }

    public static String getQRSkuCode(Context context, String qrCode) {
        int beforeX = PreferencesUtils.getInt(context, ConstantPreference.QR_SKU_BEFOREX);
        int afterX = PreferencesUtils.getInt(context, ConstantPreference.QR_SKU_AFTERX);
        int radioButton = PreferencesUtils.getInt(context, ConstantPreference.QR_SKU_RADIOBUTTONID);
        return spliteCode(context, qrCode, radioButton, beforeX, afterX);
    }

    public static String getQRSnCode(Context context, String qrCode) {
        int beforeX = PreferencesUtils.getInt(context, ConstantPreference.QR_SN_BEFOREX);
        int afterX = PreferencesUtils.getInt(context, ConstantPreference.QR_SN_AFTERX);
        int radioButton = PreferencesUtils.getInt(context, ConstantPreference.QR_SN_RADIOBUTTONID);
        return spliteCode(context, qrCode, radioButton, beforeX, afterX);
    }

    public static String spliteCode(Context context, String code, int radioButton, int beforeX, int afterX) {
        String splitCode = "";

        boolean isOpen = PreferencesUtils.getBoolean(context, ConstantPreference.QRCODE_IS_OPEN);
        if (!isOpen) {
            return code;
        }

        try {
            switch (radioButton) {
                case 0:
                    splitCode = code.substring(beforeX - 1, afterX);
                    break;
                case 1:
                    splitCode = code.substring(0, beforeX);
                    break;
                case 2:
                    splitCode = code.substring(code.length() - afterX);
                    break;
                case 3:
                    splitCode = code.substring(beforeX);
                    break;
                case 4:
                    splitCode = code.substring(0, code.length() - afterX);
                    break;
            }
        } catch (Exception e) {
            splitCode = "";
        }
        return splitCode;
    }

    /**
     * 获取焦点（可解决无法获取焦点的问题）
     *
     * @param editText
     */
    public static void requestFocusAndClearText(final EditText editText) {
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                editText.setText("");
                editText.requestFocus();
            }
        }, 50);
    }

    /**
     * 获取焦点（可解决无法获取焦点的问题）
     *
     * @param editText
     */
    public static void requestFocusAndNoClearText(final EditText editText) {
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                String text = editText.getText().toString().trim();
                editText.setSelection(text.length());
                editText.selectAll();
                editText.requestFocus();
            }
        }, 20);
    }

    public static boolean checkHttpUrl(String url) {
        boolean isTrue = true;
        //正则表达式
        String regUrl = "^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\\\/])+$";
        Pattern p = Pattern.compile(regUrl);
        Matcher m = p.matcher(url);
        if (!m.matches()) {
            isTrue = false;
        }
        return isTrue;
    }

    public static <T> T checkNotNull(T object, String message) {
        if (object == null) {
            throw new NullPointerException(message);
        }
        return object;
    }

    /**
     * string.xml字符串拼接
     *
     * @param context 上下文
     * @param resId   资源id
     * @param addData 添加的数据
     * @return
     */
    public static String getTvAddInfo(Context context, int resId, String addData) {
        return context.getResources().getString(resId, addData);
    }

    /**
     * Map转换成List集合
     *
     * @param map
     * @param <T>
     * @param <V>
     * @return
     */
    public static <T, V> List<T> setMapToList(Map<V, T> map) {
        List<T> list = new ArrayList<>();
        Set<Map.Entry<V, T>> entryMap = map.entrySet();
        for (Map.Entry<V, T> entry : entryMap) {
            list.add(entry.getValue());
        }
        return list;
    }

    /**
     * 前3后4中间三位加密
     *
     * @param mobile
     * @return
     */
    public static String getPhone(String mobile) {
        if (StringUtils.isEmpty(mobile))
            return "";
        return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    /**
     * 前3后4中间三位加密
     *
     * @param card
     * @return
     */
    public static String getVipCard(String card) {
        if (StringUtils.isEmpty(card))
            return "";
        return card.replaceAll("(.{3})(?:.+)(.{4})", "$1****$2");
    }

    /**
     * 格式化空字符串
     *
     * @param formatValue 格式化的字符串
     *                    默认给0值
     * @return
     */
    public static String formatEmptyStringZero(String formatValue) {
        return formatEmptyString(formatValue, "0");
    }

    /**
     * 字符串格式化成int
     *
     * @param data
     * @return
     */
    public static byte formatStringToByte(String data) {
        byte num = 0;
        try {
            if (TextUtils.isEmpty(data)) {
                return num;
            }
            return Byte.parseByte(data);
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 字符串格式化成char
     *
     * @param data
     * @return
     */
    public static char formatStringToCharAt(String data) {
        char num = '0';
        try {
            if (TextUtils.isEmpty(data)) {
                return num;
            }
            return data.charAt(0);
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 字符串格式化成double
     *
     * @param data
     * @return
     */
    public static double formatStringToShort(String data) {
        short num = 0;
        try {
            if (StringUtils.isEmpty(data)) {
                return num;
            }
            num = Short.parseShort(data);
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 字符串格式化成Float
     *
     * @param data
     * @return
     */
    public static float formatStringToFloat(String data) {
        float num = 0;
        try {
            if (TextUtils.isEmpty(data)) {
                return num;
            }
            return Float.parseFloat(data);
        } catch (Exception e) {
        }
        return num;
    }

    public static String formatEmptyString(String formatValue, String value) {
        if (StringUtils.isEmpty(formatValue))
            return value;
        return formatValue;
    }

    /**
     * double去掉多余的0
     * 3.10 - 3.1
     * 3.00- 3
     *
     * @param formatValue 传入个double值
     * @return
     */
    public static String formatDoubleToString(double formatValue) {
        return formatDoubleToString(formatValue, 2);
    }

    private static String formatDoubleToString(double formatValue, int length) {
        StringBuilder formatStr = new StringBuilder("#");
        if (length == 2) {
            formatStr.append(".##");
        } else {
            if (length > 0) {
                formatStr.append(".");
                for (int i = 0; i < length; i++) {
                    formatStr.append("#");
                }
            }

        }
        DecimalFormat nf = new DecimalFormat(formatStr.toString());
//        nf.setRoundingMode(RoundingMode.DOWN);
        return nf.format(formatValue);
    }

    /**
     * 格式化double类型字符串(0.00)
     *
     * @param s
     * @return String
     */
    public static String doubleFormat(String s) {
        double d = Double.parseDouble(s);
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(d);
    }

    /**
     * 格式化double小数点后两位(0.00)
     *
     * @param d
     * @return String
     */
    public static String doubleDecimalFormat(double d) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(d);
    }

    /**
     * 随机uuido
     *
     * @return
     * @author LiJiaJian
     */
    public static String getUUIDRandom() {
        return UUID.randomUUID().toString();
    }

    /**
     * 随机生成验证码
     *
     * @param length 验证码位数
     * @return
     */
    public static String getRandomICode(int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(String.valueOf(new Random().nextInt(10)));
        }
        return sb.toString();
    }

    /**
     * 将传入的值转为正的
     *
     * @param d
     * @return
     */
    public static double setPositive(double d) {
        if (d < 0) {
            return d * -1;
        }
        return d;
    }

    /**
     * 格式化金钱
     * 华为P9，Meta8，Meta9金额用Locale.CHINA显示为一杆金钱,采用替换符号的方式
     * 荣耀4C格式化负数  如-99 格式化成（￥99）
     *
     * @param data
     * @return
     */
    public static String formatMoney(double data) {

        String result = "￥" + String.format("%.2f", data);
//        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
//        String result = numberFormat.format(data);
//        if (result.contains("-")) {
//            result = result != null && result.length() > 0 ? ("￥-" + result.substring(2)) : "";
//        } else if (result.contains("(")) {
//            result = result.replace("(", "").replace(")", "");
//            result = result != null && result.length() > 0 ? ("￥-" + result.substring(1)) : "";
//        } else {
//            result = result != null && result.length() > 0 ? ("￥" + result.substring(1)) : "";
//        }

        return result;
    }

    /**
     * 安装APP
     *
     * @param url
     * @param context
     */
    public static void installApp(String url, Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(url)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 固定长度数字位数不够前面补0
     *
     * @param number
     * @return
     */
    public static String getMulNo(int length, int number) {
        String result = String.format("%0" + length + "d", number);
        return result;
    }

    /**
     * 格式化金钱
     *
     * @param data
     * @return
     */
    public static String formatMoney(String data) {
        double num = 0;
        try {
            num = Double.parseDouble(data);
        } catch (Exception e) {
        }
        return formatMoney(num);
    }

    /**
     * 字符串格式化成double
     *
     * @param data
     * @return
     */
    public static double formatStringToDouble(String data) {
        double num = 0;
        try {
            if (StringUtils.isEmpty(data)) {
                return num;
            }
            num = Double.parseDouble(data);
        } catch (Exception ignored) {
        }
        return num;
    }

    /**
     * 添加空字符,针对三个字符处理
     *
     * @return
     */
    public static String addEmpty(String one, String two, String three, int addLength) {
        int oneLength = 18;
        int twoLength = 31;
        int threeLength = 48;
        String totalStr = "";
        for (int i = 0; i < oneLength - one.length(); i++) {
            totalStr += " ";
        }
        totalStr += one;
        for (int i = 0; i < twoLength - oneLength - two.length(); i++) {
            totalStr += " ";
        }
        totalStr += two;
        for (int i = 0; i < threeLength - twoLength - three.length() - addLength; i++) {
            totalStr += " ";
        }
        totalStr += three;

        return totalStr;
    }

    /**
     * 支付使用添加字符
     *
     * @param name
     * @return
     */
    public static int addLength(String name) {
        return name.length() - 2;
    }

    /**
     * 格式化成小数点
     *
     * @param price    需要格式化的值
     * @param newScale 保留小数位
     * @param isUp     true向上取整，false抹掉小数
     * @return 格式化后的值
     */
    public static double formatDouble(double price, int newScale, boolean isUp) {
        BigDecimal b3 = new BigDecimal(Double.toString(price));
        return b3.setScale(newScale, isUp ? BigDecimal.ROUND_HALF_UP : BigDecimal.ROUND_FLOOR).doubleValue();
    }


    /**
     * 格式化成整形
     *
     * @param price 需要格式化的值
     * @param isUp  true向上取整，false抹掉小数
     * @return 格式化后的值
     */
    public static int formatInt(double price, boolean isUp) {
        return (int) formatDouble(price, 0, isUp);
    }

    /**
     * 添加空字符
     *
     * @return
     */
    public static String addEmpty(String left, String right, int addLength) {
        int totalLength = "---------------------------------------------".length();
        String totalStr = left;
        if (left.length() + right.length() < totalLength) {
            for (int i = 0; i < totalLength - left.length() - right.length() - addLength; i++) {
                totalStr += " ";
            }
        }
        totalStr += right;
        return totalStr;
    }

    /**
     * 添加空字符
     *
     * @return
     */
    public static String addEmpty(String left, String right, int addLength, int addRight) {
        int totalLength = 48;
        String totalStr = left;
        if (left.length() + right.length() < totalLength) {
            for (int i = 0; i < totalLength - left.length() - right.length() - addLength; i++) {
                totalStr += " ";
            }
        }
        totalStr += right;
        return totalStr;
    }

    /**
     * 保持小数点后的两位
     *
     * @return
     */
    public static String formatStringPointTwo(String data) {
        double result;
        try {
            result = Double.parseDouble(data);
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(2);
            df.setMinimumFractionDigits(2);
            data = new java.text.DecimalFormat("#0.00").format(result);
        } catch (Exception e) {

        }
        return data;
    }

    /**
     * 保持小数点后的两位
     *
     * @return
     */
    public static String formatStringPointZero(String data) {
        double result;
        try {
            result = Double.parseDouble(data);
            DecimalFormat df = new DecimalFormat();
            df.setMaximumFractionDigits(0);
            df.setMinimumFractionDigits(0);
            data = new java.text.DecimalFormat("#0").format(result);
        } catch (Exception e) {

        }
        return data;
    }

    /**
     * 字符串格式化成int
     *
     * @param data
     * @return
     */
    public static int formatStringToInt(String data) {
        int num = 0;
        try {
            if (StringUtils.isEmpty(data)) {
                return num;
            }
            num = (int) CommonUtil.formatStringToDouble(data);
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 字符串格式化成int
     *
     * @param data
     * @return
     */
    public static long formatStringToLong(String data) {
        long num = 0;
        try {
            if (StringUtils.isEmpty(data)) {
                return num;
            }
            num = Long.parseLong(data);
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 带小数点字符串格式化成int
     *
     * @param data
     * @return
     */
    public static int formatStringNumberToInt(String data) {
        int num = 0;
        try {
            if (StringUtils.isEmpty(data)) {
                return num;
            }
            double douNum = Double.parseDouble(data);
            num = (int) douNum;
        } catch (Exception e) {
        }
        return num;
    }

    /**
     * 字符串设置为空
     *
     * @param data
     * @return
     */
    public static String formatStringToEmpty(String data) {
        if (TextUtils.isEmpty(data)) {
            return "";
        }
        return data;
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    //获取包名
    public static String getPackageName(Context context) {
        return getPackageInfo(context).packageName;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /**
     * 判断字符串是否为Double类型
     *
     * @param data
     * @return
     */
    public static boolean StringIsDouble(String data) {
        try {
            double num = Double.parseDouble(data);
            return true;
        } catch (Exception e) {
        }
        return false;
    }


    /**
     * View生成图片
     */
    public static boolean viewSaveToImage(Bitmap bitmap, String fileName) {
        if (bitmap == null) {
            return false;
        }
        // 添加水印
//        Bitmap bitmap = Bitmap.createBitmap(createWatermarkBitmap(cachebmp,
//                "huawei"));
        FileOutputStream fos;
        try {
            // 判断手机设备是否有SD卡
            String path = CacheDirectoryManager.getInstance().getResourceDownloadPath();
            if (!StringUtils.isEmpty(path)) {
                // SD卡根目录
                File file = new File(path, fileName);
                fos = new FileOutputStream(file);
            } else {
                throw new Exception("创建文件失败!");
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();
            bitmap.recycle();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * View卸载画布上
     *
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromView(View v) {
        try {
            int w = v.getWidth();
            int h = v.getHeight();

            Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas c = new Canvas(bmp);
            c.drawColor(Color.WHITE);
            /** 如果不设置canvas画布为白色，则生成透明 */
            v.layout(0, 0, w, h);
            v.draw(c);
            return bmp;
        } catch (Exception e) {
            Log.d(TAG, "loadBitmapFromView: " + e);
        }
        return null;
    }

    /**
     * 格式化字符串，输入的字符是添加在前面还在后面
     *
     * @param value  当前已经有的字符串
     * @param source 输入字符串
     * @param dstart 切断的索引值
     * @return
     */
    public static String formatInputStr(String value, String source, int dstart) {
        boolean isAddBefore = false;
        if (value.contains(".")) {
            String[] s = value.split("[.]");
            String beforeStr = "";
            if (s.length > 0) {
                beforeStr = s[0];
            }
            if (beforeStr.length() >= dstart) {
                isAddBefore = true;
            }
        }
        if (isAddBefore) {
            value = source + value;
        } else {
            value = value + source;
        }
        return value;
    }

    /**
     * View卸载画布上
     *
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromWhite(Bitmap v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        return bmp;
    }


    public static boolean isNumber(Object obj) {
        try {
            Double.parseDouble(obj.toString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isZero(Object obj) {
        try {
            if (0 != Double.parseDouble(obj.toString()))
                return false;
            else
                return true;
        } catch (Exception e) {
            return true;
        }
    }

    public static boolean isShort(Object obj) {
        try {
            Short.parseShort(obj.toString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isInt(Object obj) {
        try {
            Integer.parseInt(obj.toString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isLong(Object obj) {
        try {
            Long.parseLong(obj.toString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean isDouble(Object obj) {
        try {
            Double.parseDouble(obj.toString());

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static double toDouble(Object obj) {
        try {
            if (obj == null)
                return 0;
            return Double.parseDouble(obj.toString());
        } catch (Exception e) {
            return 0;
        }
    }

    public static int toInt(char c) {
        try {
            return Character.getNumericValue(c);
        } catch (Exception e) {
            return 0;
        }

    }

    public static short toShort(Object obj) {
        try {
            return (short) toDouble(obj);
        } catch (Exception e) {
            return 0;
        }
    }

    public static int toInt(Object obj) {
        try {
            return (int) toDouble(obj);
        } catch (Exception e) {
            return 0;
        }
    }

    public static long toLong(Object obj) {
        try {
            return (long) toDouble(obj);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 计算字符串长度 中文 占2个字节
     */

    public static int countLength(String line) {
        int length = 0;

        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);

            if ((int) c > 127) {
                length += 2;
            } else {
                length += 1;
            }
        }

        return length;
    }


    /**
     * 截取新字符串 中文 占2个字节
     */

    public static String newSubString(String line, int start) {
        return newSubString(line, start, countLength(line));
    }

    public static String newSubString(String line, int start, int end) {
        if (start >= end) {
            return "";
        }

        if (countLength(line) <= (end - start)) {
            return line;
        }

        boolean flag = false;
        int startindex = 0;
        int endindex = 0;
        int length = 0;

        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);

            if ((int) c > 127) {
                length += 2;
            } else {
                length += 1;
            }

            if (length >= (end + 1)) {
                endindex = i;

                break;
            }

            if ((length >= (start + 1)) && !flag) {
                flag = true;
                startindex = i;
            }
        }

        if (startindex > endindex) {
            return line.substring(startindex);
        } else {
            return line.substring(startindex, endindex);
        }
    }

    public static String getPrintText(String leftLine, int leftLen, String rightLine, int rightLen, int length, int orgSize, int alignment) {
        return "";
    }

    /**
     * 打印字符串处理
     *
     * @startIndex:添加到原始字符串的指定位置
     * @length:添加字符串的指定长度
     * @orgSize:原始字符串的指定长度
     */

    public static String appendStringSize(String orgLine, String addLine, int startIndex, int length, int orgSize, int alignment) {
        String newLine = orgLine;

        // 将原始字符串 添加或删除到指定长度
        int orgLength = countLength(orgLine);

        if (orgLength > orgSize) {
            newLine = newSubString(orgLine, 0, orgSize);
        } else {
            for (int i = orgLength; i < orgSize; i++) {
                newLine += " ";
            }
        }

        // 如果需要修改某段字符串
        if (addLine != null) {
            // 取需要添加字符串的最小值为指定添加长度
            if (countLength(addLine) >= length) {
                addLine = newSubString(addLine, 0, length);
            } else {
                int sub = 0;
                switch (alignment) {
                    case 0:
                        sub = 0;
                        break;
                    case 1:
                        sub = (length - countLength(addLine));
                        break;
                    case 2:
                        sub = (length - countLength(addLine)) / 2;
                        break;
                }

                for (int i = countLength(addLine); i < length; i++) {
                    if (sub > 0) {
                        addLine = " " + addLine;
                        sub--;
                    } else {
                        addLine += " ";
                    }
                }
            }
            // 截取
            String head = newSubString(newLine, 0, startIndex);
            String end = "";

            try {
                end = newSubString(newLine, startIndex + length, orgSize);
            } catch (Exception er) {
                er.printStackTrace();
            }

            // 修改后的字符串
            newLine = head + addLine + end;

            if (countLength(newLine) > orgSize) {
                newLine = newSubString(newLine, 0, orgSize);
            }
        }

        return newLine;
    }

    // 0:左对齐 1； 右对齐 2；中间
    public static String appendStringSize(String orgLine, String addLine, int startIndex, int length, int orgSize) {
        return appendStringSize(orgLine, addLine, startIndex, length, orgSize, 0);
    }

    // 0:左对齐 1； 右对齐 2；中间
    public static String splitString(String orgLine, String addLine, int length) {
        int orgLength = countLength(orgLine);
        if (orgLength <= length) {
            return orgLine + addLine;
        }
        String newLine = "";
        int startIndex = 0;
        while (startIndex < orgLength) {
            newLine = newLine + newSubString(orgLine, startIndex, startIndex + length) + addLine;
            startIndex = startIndex + length;
        }
        return newLine;
    }

    /**
     * 判断字符是否为字母
     *
     * @param c
     * @return
     */
    public static boolean isLetter(char c) {
        if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 重复放入字符拼成字符串
     *
     * @param c
     * @return
     */
    public static String fill(String c, int len) {
        String result = "";
        for (int i = 0; i < len; i++)
            result = result + c;

        return result;
    }

    /**
     * @param leftLine
     * @param leftSize       占用长度
     * @param leftAlignment  0:左对齐 1； 右对齐 2；中间
     * @param rightLine
     * @param rightSize      占用长度
     * @param rightAlignment 0:左对齐 1； 右对齐 2；中间
     * @param orgSize        行的总长度
     * @return
     */
    public static String getPrintText(String leftLine, int leftSize, int leftAlignment, String rightLine, int rightSize, int rightAlignment, int orgSize) {
        String tmpString = "";
        String result = "";
        tmpString = appendStringSize("", leftLine, leftSize - countLength(leftLine), countLength(leftLine), leftSize, leftAlignment);
        result = appendStringSize(tmpString, rightLine, orgSize - rightSize, rightSize, orgSize, rightAlignment);
        return result;
    }

    /**
     * 截取日期字符串
     *
     * @param dateStr
     * @return YYYY-MM-DD HH:MM
     */
    public static String subDateStr(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.length() < "YYYY-MM-DD HH:MM".length()) {
            return dateStr;
        }
        return dateStr.substring(0, "YYYY-MM-DD HH:MM".length());
    }

    public static String getShowDateStr(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return "";
        }
        if (dateStr.length() <= "YYYY-MM-DD".length()) {
            return dateStr;
        }
        return dateStr.substring(0, "YYYY-MM-DD".length());
    }

    /**
     * 标准日期格式转成日期字符串
     */
    public static String toDateStr(String dateStr) {
        Date date = null;
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        try {
            date = sdf1.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdf2.format(date);
    }

    /**
     * 获取绝对值
     *
     * @param value
     * @return
     */
    public static double getPositiveValue(double value) {
        if (value >= 0) {
            return value;
        } else {
            return value * -1;
        }
    }

    public static double getPositiveValue(String value) {
        double result = formatStringToDouble(value);
        return getPositiveValue(result);
    }

    /**
     * 获取错误信息
     *
     * @param errorMsg
     * @param defaultMsg 默认提示
     * @return
     */
    public static String getErrorMsg(String errorMsg, String defaultMsg) {
        if (!TextUtils.isEmpty(errorMsg)) {
            return errorMsg;
        }
        return defaultMsg;
    }

}
